
import requests
import jwt
import time
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend
import gzip
import io
from .ReportTypes import Frequency, ReportType, ReportSubType

''' App Store Connect API '''
class AppStoreConnectAPI:
    
    def __init__(self, api_key_path, api_issuer_id, api_key_id):
        self.api_issuer_id = api_issuer_id
        self.api_key_id = api_key_id
        self.jwt_token = self._generate_api_key(api_key_path)

    def _generate_api_key(self, api_key_path):
        # Load the private key
        with open(api_key_path, 'rb') as key_file:
            private_key = serialization.load_pem_private_key(
                key_file.read(),
                password=None,
                backend=default_backend()
            )

        jwt_payload = {
            'iss': self.api_issuer_id,
            'exp': time.time() + 2*60,
            'aud': 'appstoreconnect-v1'
        }

        jwt_headers = {
            'alg': 'ES256',
            'kid': self.api_key_id,
            'typ': 'JWT'
        }

        tokens = jwt.encode(jwt_payload, private_key, algorithm='ES256', headers=jwt_headers) # type: ignore
        return tokens

    def _get_headers(self):
        return {
            'Authorization': f'Bearer {self.jwt_token}',
            'Content-Type': 'application/json'
        }

    def get_app_info(self, app_id):
        url = f"https://api.appstoreconnect.apple.com/v1/apps/{app_id}"
        response = requests.get(url, headers=self._get_headers())
        return response.json()

    def get_all_apps(self):
        url = "https://api.appstoreconnect.apple.com/v1/apps?limit=2"
        response = requests.get(url, headers=self._get_headers())
        return response.json()
    
    ''' Get vendors '''
    def get_vendors(self):
        url = "https://api.appstoreconnect.apple.com/v1/vendors"
        response = requests.get(url, headers=self._get_headers())
        return response.json()
    
    def get_analytics_report(self, app_id, access_type="ONGOING"):
        url = "https://api.appstoreconnect.apple.com/v1/analyticsReportRequests"
        response = requests.get(url, headers=self._get_headers())
        
        body = {
            "data": {
                "type": "analyticsReportRequests",
                "attributes": {
                    "accessType": access_type,
                },
                "relationships": {
                    "app": {
                        "data": {
                            "type": "apps",
                            "id": app_id
                        }
                    }
                }
            }
        }
        
        return response.json()
    
    def get_sales_report(self, vendor_id, report_date, frequency:Frequency = Frequency.daily, report_type:ReportType = ReportType.sales, report_sub_type:ReportSubType = ReportSubType.summary, version = '1_1'):
        params = {
            "filter[frequency]": frequency.value,
            "filter[reportType]": report_type.value,
            "filter[reportSubType]": report_sub_type.value,
            "filter[vendorNumber]": vendor_id,
            "filter[version]": version,
            "filter[reportDate]": report_date
        }
        url = "https://api.appstoreconnect.apple.com/v1/salesReports"
        response = requests.get(url, headers=self._get_headers(), params=params)

        
        # Check if the request was successful
        if response.status_code == 200:
            if response.headers['Content-Type'] == 'application/a-gzip':
                compressed_report = io.BytesIO(response.content)
                decompressed_report = gzip.GzipFile(fileobj=compressed_report)

                return decompressed_report
            else:
                print("Error: The response is not a gzip file.")
                return None
        else:
            print(f"Error: {response.text}")
            # 返回Nothing
            return None
